<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !purchAppDetailinfo.visible &&
        !summaryDetailInfo.visible &&
        !modifyInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList"> </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :check-box="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('purchOrder:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
        <template v-slot:col-applicationNo="scope">
          <span
            v-if="$permission('purchApplication:detail')"
            class="slip-edit"
            @click="showPurchAppDetail(scope.row)"
            >{{ scope.row.applicationNo || '-' }}</span
          >
          <span v-else>{{ scope.row.applicationNo || '-' }}</span>
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <summary-purch-order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <purch-application-detail
      v-if="purchAppDetailinfo.visible"
      v-model:visible="purchAppDetailinfo.visible"
      :table-row="purchAppDetailinfo.data"
      @returnBack="getList"
    />
    <purch-application-summary-detail
      v-if="summaryDetailInfo.visible"
      v-model:visible="summaryDetailInfo.visible"
      :table-row="summaryDetailInfo.data"
      @returnBack="getList"
    />
    <select-order
      v-if="showSelectOrder"
      v-model:show-dialog="showSelectOrder"
      :query="showSelectOrderQuery"
      @callback="callbackOrder"
    ></select-order>

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
  </div>
</template>

<script setup name="purchOrderSummary">
import {
  fatchPurchOrderSummaryCustomizeListPage,
  deletePurchOrderSummaryPage,
  methodPurchOrderSummary,
} from '@/api/purch'
import { getCustomizeSetting } from '@/api/customize'
import { getReceiveAddressAll } from '@/api/core'
import { updateUserCustomize } from '@/api/customize'
import summaryPurchOrderDetail from './detail'
import SelectOrder from './selectOrder'
import PurchApplicationDetail from '../application/detail'
import PurchApplicationSummaryDetail from '@/views/purch/applicationSummary/detail'
const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    groupMap: {},
    groups: [],
    queryParams: {},
    queryMap: {
      supplierAuth: {
        asTbName: 'purch_order_summary',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('purchOrderSummary:add'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: (row) => handelMethodRequest(row, 'submit'),
        show: proxy.$permission('purchOrderSummary:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: (row) => handelDeletePurchOrderSummaryPage(row),
        show: proxy.$permission('purchOrderSummary:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: (row) => handelMethodRequest(row, 'revoke'),
        show: proxy.$permission('purchOrderSummary:revoke'),
        ifRender: function (row) {
          let type = false
          if (row.status === 2) {
            type = true
          } else if (row.status === 3) {
            if (row.beforeMergeStatus === 3) {
              type = true
            } else {
              type = false
            }
          }
          return type
        },
      },
      {
        label: '批准',
        event: (row) => handelMethodRequest(row, 'ratify'),
        show: proxy.$permission('purchOrderSummary:ratify'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '采购',
        event: (row) => handelMethodRequest(row, 'doPurch'),
        show: proxy.$permission('purchOrder:doPurch'),
        ifRender: function (row) {
          return (
            row.status === 3 ||
            (row.status === 9 &&
              proxy.$store.state.permission.systemConfig
                .supplier_refuse_purch_again == 1)
          )
        },
      },
      {
        label: '整单驳回',
        event: (row) => handelMethodRequest(row, 'reject'),
        show: proxy.$permission('purchOrderSummary:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '中止',
        event: (row) => handelMethodRequest(row, 'stop'),
        popconfirmText: '中止后将改变数据,是否继续？',
        show: proxy.$permission('purchOrderSummary:stop'),
        ifRender: function (row) {
          let type = false
          if (row.status === 8 || row.status === 7) {
            type = true
          } else if (row.status === 3) {
            if (row.beforeMergeStatus === 2) {
              type = true
            } else {
              type = false
            }
          }
          return type
        },
      },
    ],
  },
})
const showSelectOrder = ref(false)
const showSelectOrderQuery = ref({})
const modifyInfo = ref({
  visible: false,
  title: '',
  purchOrderSummaryId: '',
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
//明细相关
const detailInfo = ref({
  visible: false,
  title: '采购单明细',
})
const purchAppDetailinfo = ref({
  visible: false,
  title: '申购单明细',
  data: {},
})
const summaryDetailInfo = ref({
  visible: false,
  title: '申购单汇总明细',
  data: {},
})
const purchOrderCheckApplicationInfo = ref({
  visible: false,
  title: '生成采购单',
  purchApplicationId: null,
})

const canDelete = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 1).length !== 0
  )
})
const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 1).length !== 0
  )
})
const canRatify = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 2).length !== 0
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 2).length !== 0
  )
})
const canStop = computed(() => {
  return (
    tableInfo.value.selections.filter(
      (item) => item.status === 7 || item.status === 8
    ).length !== 0
  )
})

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'purch_order_summary_status',
      show: false,
      hidden: true,
    },
    beforeMergeStatusValue: {
      label: '状态',
      value: 'beforeMergeStatusValue',
      asValue: 'beforeMergeStatus',
      componentType: 'select-model',
      code: 'purch_order_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.value.purchOrderSummaryId) {
    getList()
  } else {
    search()
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  let arr = [
    {
      asTbName: 'purch_order_summary',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.visible = true
  detailInfo.value.data = { ...row }
}
function showPurchAppDetail(row) {
  let obj = {}
  sessionStorage.setItem('storeRowId', row.id)
  obj = JSON.parse(JSON.stringify(row))
  obj.id = row.applicationId
  let purchType = row.purchType
  if (purchType === 0) {
    purchAppDetailinfo.value.visible = true
    purchAppDetailinfo.value.data = { ...obj }
  } else if (purchType === 1) {
    summaryDetailInfo.value.visible = true
    summaryDetailInfo.value.data = { ...obj }
  }
}
function handelMethodRequest(row = undefined, method) {
  const ids = getSelectionIds(row)
  if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: row.id,
          rejectReason: value,
        }
        methodPurchOrderSummary(data, method).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  } else {
    methodPurchOrderSummary(ids, method).then((resp) => {
      if (resp.success) {
        tableInfo.value.refresh = Math.random()
      }
    })
  }
}
function handelDeletePurchOrderSummaryPage(row = undefined) {
  const ids = getSelectionIds(row)
  deletePurchOrderSummaryPage(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function getSelectionIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map(function (item) {
      return item.id
    })
  }
  return ids
}
//生成采购单
function generatePurchOrder(row) {
  const params = {
    isDefault: 'yes',
  }
  getReceiveAddressAll(params).then((resp) => {
    if (resp && resp.success) {
      purchOrderCheckApplicationInfo.value.visible = true
      purchOrderCheckApplicationInfo.value.purchApplicationId = row.id
    }
  })
}
//删除
function deleteOrder(row) {
  deletePurchOrderSummaryPage([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
// 创建
function create() {
  showSelectOrder.value = true
}
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改采购汇总单'
  // 显示信息
  modifyInfo.value.purchOrderId = data.id
}
function callbackOrder() {
  getList()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'purchOrderSummaryList-com.slip.spd.entity.vo.purch.PurchOrderSummaryVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = fatchPurchOrderSummaryCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
